// stores/fileStore.ts
import { create } from 'zustand'
import { commonService } from '@/services'
import { formatRelativeTime } from '@/lib/utils'
import { type ResourceQuery, type TagItem } from '@/services'

// 内部类型定义
export type FileType = 'mp3' | 'mp4' | 'wav' | 'jpg' | 'png' | 'svg' | 'gif'

export type TimeRange = '全部' | '今天' | '最近7天' | '最近30天' | '更早'

export interface FilterState {
  type: FileType | '全部'
  timeRange: TimeRange
  sortBy: '时间升序' | '时间降序' | '名称升序' | '名称降序'
  tags: string
  public: string
}

export interface FileItem {
  id: string
  name: string
  type: string
  duration: string
  url: string
  thumbnail: string
  fileType: string
  selected?: boolean
  ext: string
  tags?: string[]
  public?: 0 | 1
}

export type MediaType = 'video' | 'audio' | 'image'

interface FileStore {
  files: FileItem[]
  tagList: TagItem[]
  totalRecords: number
  setFiles: (files: FileItem[]) => void
  fetchFiles: (params: ResourceQuery) => void
  getTagList: () => void
}

export const useFileStore = create<FileStore>((set) => ({
  files: [],
  tagList: [],
  totalRecords: 0,
  setFiles: (files) => {
    set({ files })
  },
  getTagList: async () => {
    const res = await commonService.getResourceTagList()
    set({ tagList: res })
  },
  fetchFiles: async (params: ResourceQuery) => {
    const res = await commonService.resourceList(params)
    const dataList: FileItem[] = res.data.map((item) => {
      const { fileType } = getFileType(item.ext)
      const fileUrl: Record<MediaType, string> = {
        video: '/file-video.svg',
        audio: '/file-audio.svg',
        image: item.url,
      }
      return {
        id: item.id + '',
        name: item.name,
        type: item.ext as FileType,
        duration: formatRelativeTime(new Date(item.updated_at)),
        url: item.url,
        thumbnail: fileUrl[fileType] || item.url,
        fileType,
        ext: item.ext,
        public: item.public,
        tags:
          item.tags?.map((item) => {
            return item.name
          }) ?? [],
        // tags: item.tags,
      }
    })

    set({
      files: dataList,
      totalRecords: res.total, // 确保 API 返回总记录数
    })
    // set((state) => {
    //   state.setFiles(dataList)
    //   return state
    // })
  },
}))

export function getFileType(type: string) {
  const isMp3 = type === 'mp3'
  const isVideo = type === 'mp4' || type === 'wav' || type === 'mov'
  const isImage =
    type === 'jpg' || type === 'png' || type === 'svg' || type === 'gif'

  let title = ''
  let fileType = ''

  if (isMp3) {
    title = 'Preview Audio'
    fileType = 'audio'
  } else if (isVideo) {
    title = 'Preview Video'
    fileType = 'video'
  } else if (isImage) {
    title = 'Preview Image'
    fileType = 'image'
  }
  return {
    title,
    fileType: fileType as MediaType,
  }
}
